package case3;

import java.util.PriorityQueue;
import java.util.TimerTask;

class MyTimeTask implements Comparable<MyTimeTask>{

    private PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();
    private Runnable runnable;
    private long time;
    private Object locker = new Object();


    public MyTimeTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public long getTime() { return time;}
    public Runnable getRunnable() { return runnable;}

    @Override
    public int compareTo(MyTimeTask o){
        return (int) (this.time - o.time);
    }
}

class MyTime{

    private PriorityQueue<MyTimeTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay){
        synchronized (locker){
            queue.offer(new MyTimeTask(runnable, delay));
            locker.notify();
        }
    }

    public MyTime(){
        Thread t = new Thread(() -> {
           while(true){
               try{
                   synchronized (locker){
                       while(queue.isEmpty()){
                           locker.wait();
                       }
                       MyTimeTask task = queue.peek();
                       long curTime = System.currentTimeMillis();
                       if(curTime >= task.getTime()){
                           task.getRunnable().run();
                           queue.poll();
                       }else{
                           locker.wait(task.getTime() - curTime);
                       }
                   }
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
           }
        });
        t.start();
    }
}

public class Demo2 {
    public static void main(String[] args) {
        MyTime timer = new MyTime();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);

        System.out.println("程序启动");
    }
}
